package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.lang.ArrayUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyLauncher {
	public static void main(String[] args) throws Exception {
		//configure this to the absolute path
		String proj_path = "/home/tuul/workspace/poker_app2/";
		
		WebAppContext wac = new WebAppContext();
		wac.setResourceBase(proj_path+"WebContent");
		wac.setDescriptor(proj_path+"WebContent/web.xml");
		wac.setContextPath("/");
		//wac.setDefaultCacheDuration(3600); 
		//gzipResources(proj_path+"WebContent");
		
		wac.setParentLoaderPriority(true);
		
		Server server = new Server(8030);
		server.setHandler(wac);
		server.start();        
    }
	
	private static void gzipResources(String path) {
		System.out.println("Gzipping");
		//Gzip all the files in the following directories
		String[] folder_list = {"/script", "/img"};
		String ext;
		
		File[] file_list = {};		
		for (String folder_name : folder_list) {
			File folder = new File(path+folder_name);
			System.out.println("Looking into folder : " + path + folder_name);
			file_list = folder.listFiles();
			for (File file : file_list) {
				try {
					ext = file.getName().substring(file.getName().lastIndexOf("."),file.getName().length());
					if (!ext.equals(".js") && !ext.equals(".css")) continue;
			        // Create the GZIP output stream
			        String outFilename = path+folder_name + "/" + file.getName() + ".gz";
			        System.out.println("Gzipping into : " + outFilename);
			        GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFilename));
			    
			        // Open the input file
			        String inFilename = path+folder_name + "/" + file.getName();
			        FileInputStream in = new FileInputStream(inFilename);
			    
			        // Transfer bytes from the input file to the GZIP output stream
			        byte[] buf = new byte[1024];
			        int len;
			        while ((len = in.read(buf)) > 0) {
			            out.write(buf, 0, len);
			        }
			        in.close();
			    
			        // Complete the GZIP file
			        out.finish();
			        out.close();
			    } catch (IOException e) {
			    }
			}
		}		
				
	}
}